# -*- coding: utf-8 -*-
import os
import time
import uuid
from app.model.filedata import Filedata
from werkzeug.utils import secure_filename
from app import app, slash, SITE_URL, db, ALLOW_EXTENSIONS, SAVE_UPLOAD_FOLDER
from flask import request,jsonify,render_template
from app.util.file import compress_image, getMd5

@app.route("/page")
def page():
    user = {'username':'kevin'}
    names = {'username':'haha'}
    datas = [user,names]
    return render_template('index.html',datas = datas)

@app.route('/upload',methods=['GET','POST'])
def upload():
    if request.method == 'POST':
        file = request.files["file"]
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            uid = str(uuid.uuid4())
            file_name = uid + "." + filename.rsplit(".", 1)[1]
            file_name = file_name.replace("-", "")  # 保存名字
            file.save(os.path.join(app.config["UPLOAD_FOLDER"], file_name))
            base_path = os.getcwd()
            file_path = base_path + slash + app.config["UPLOAD_FOLDER"] + slash + file_name  # 保存地址

            file_hash = getMd5(app.config["UPLOAD_FOLDER"] + slash + file_name)
            hasHash = Filedata.query.filter_by(filehash=file_hash).first()
            if hasHash != None:
                return jsonify({"errno": "1", "errmsg": u"此文件已存在"})

            thumbName = (SAVE_UPLOAD_FOLDER + slash + uid + "_thumb." + filename.rsplit(".", 1)[1]).replace("-", "")
            # 如果文件大小小于要压缩的大小，不会压缩，直接返回原文件名字
            thumbBack = compress_image(app.config["UPLOAD_FOLDER"] + slash + file_name, "app/" + thumbName, 50)
            if thumbBack[1] == 0:
                saveThumb = SAVE_UPLOAD_FOLDER + slash + file_name
            else:
                saveThumb = thumbName
            filesize = os.path.getsize(app.config["UPLOAD_FOLDER"] + slash + file_name)
            filedata = Filedata(
                userid=100,
                filename=file.filename,
                fileurl=SITE_URL + SAVE_UPLOAD_FOLDER + slash + file_name,
                filehash=file_hash,
                filethumb=SITE_URL + saveThumb,
                size=filesize / 1024,
                source=1,
                created_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                updated_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
            db.session.add(filedata)
            db.session.commit()

            print(file_path)
            return jsonify({"imgnames": file.filename, "imgurls": SITE_URL + SAVE_UPLOAD_FOLDER + slash + file_name})
    else:
        title = '图床'
        return render_template('upload.html',title=title)
# {"imgnames":"1.jpg","imgurls":"http://blog.ismoon.top/links/tourist/fcf961108041305.jpg"}

def allowed_file(filename):
    return "." in filename and \
           filename.rsplit(".", 1)[1] in ALLOW_EXTENSIONS